#!/usr/bin/env python 
# -*- coding: utf-8 -*-

"""
# @Time    : 2021/1/19 16:45
# @Author  : Wang Yang
# @File    : Mail.py
"""

import time
import os
import shutil
from exchangelib import DELEGATE, Account, Credentials, Message, Mailbox, FileAttachment, Configuration, NTLM, HTMLBody
from selenium import webdriver


def read_file(file_path):
    try:
        with open(file_path, "rb") as f:
            cont = f.read()
    except Exception as e:
        raise Exception(str(e))
    return cont


def build_msg(output_dir, now):
    output_xml = output_dir+'/output.xml'
    print(output_xml)
    msg = r'<div style="font-size: 30px;"><b>AutoTest_{}</b></div><br>'.format(time.strftime("%Y-%m-%d %H:%M:%S",
                                                                                             time.localtime()))
    if os.path.exists(output_xml):
        msg += r'''<a href="{}_report.html">report</a><br>
                  <a href="{}_log.html">log</a>
        '''.format(now, now)
    return msg


def build_html_body(output_dir, now):
    report_html_file = "{}/{}_report.html".format(output_dir, now).replace('\\', '/')
    log_html_file = "{}/{}_log.html".format(output_dir, now).replace('\\', '/')
    # print(report_html_file)
    browser = webdriver.Chrome()
    browser.get(r"file:///{}".format(report_html_file))
    # browser.get(r"file:///D:/v_wbyangwang/robot_framework/report.html")
    summary_info = browser.find_element_by_xpath("//table[@class='details']").text
    html_body = "<font size='5' style='font-weight:bold'>Summary Information</font><br>"
    html_body += "<table>"
    log_file_href = browser.find_element_by_xpath("//table[@class='details']/tbody/tr[5]/td/a").get_attribute("href")
    # print(log_file_href)
    for sum_row in summary_info.splitlines():
        if 'Log File' not in sum_row:
            html_body += "<tr><td>{}</td></tr>".format(sum_row)
        else:
            # html_body += "<tr><td>Log File: <a href='{}'>{}</a></td></tr>".format(log_file_href, now+"_log.html")
            pass

    # html_body += r"<tr><td><a href='file://./{}_log.html'>log</a></td></tr>".format(now)
    html_body += "</table><br>"

    test_statistics = browser.find_element_by_id("total-stats").text
    stats_rows = test_statistics.splitlines()[6:]
    html_body += "<font size='5' style='font-weight:bold;'>Test Statistics</font><br>"
    html_body += "<table width='1000' border='1' cellpadding='1' cellspacing='1'>"
    html_body += "<tr bgcolor='#DCDCDC'><td width='40%'>Total Statistics</td><td>Total</td><td>Pass</td><td>Fail</td>" \
                 "<td>Elapsed</td></tr>"
    for idx in range(0, len(stats_rows), 2):
        html_body += "<tr>"
        html_body += r"<td>{}</td>".format(stats_rows[idx])
        for tmp_col in stats_rows[idx+1].split(' '):
            html_body += r"<td>{}</td>".format(tmp_col)
        html_body += "</tr>"
    html_body += "</table><br>"

    suite_stats = browser.find_element_by_id("suite-stats").text
    # print(suite_stats)
    suite_rows = suite_stats.splitlines()[6:]
    html_body += "<table width='1000' border='1' cellpadding='1' cellspacing='1'>"
    html_body += "<tr bgcolor='#DCDCDC'><td width='40%'>Statistics by Suite</td><td>Total</td><td>Pass</td>" \
                 "<td>Fail</td><td>Elapsed</td></tr>"
    for idx in range(0, len(suite_rows), 2):
        html_body += "<tr>"
        html_body += r"<td>{}</td>".format(suite_rows[idx])
        for tmp_col in suite_rows[idx+1].split(' '):
            html_body += r"<td>{}</td>".format(tmp_col)
        html_body += "</tr>"
    html_body += "</table><br>"

    html_body += "<font size='5' style='font-weight:bold;'>More information, please check the attachment files.</font>"
    print(html_body)
    return html_body


def send_email(subject, from_address, password, to_addresses, smtp_server, output_dir=None):
    now = time.strftime("%Y%m%d%H%M%S", time.localtime())
    print("now:{}".format(now))
    creds = Credentials(
        username=from_address,
        password=password
    )
    con = Configuration(server=smtp_server, credentials=creds, auth_type=NTLM)
    account = Account(
        primary_smtp_address=from_address,
        autodiscover=False,
        config=con,
        access_type=DELEGATE
    )
    try:
        if output_dir and os.path.exists(output_dir):
            src_report_html = "{}/{}".format(output_dir, '/report.html')
            tgt_report_html = "{}/{}_{}".format(output_dir, now, 'report.html')
            src_log_html = "{}/{}".format(output_dir, '/log.html')
            tgt_log_html = "{}/{}_{}".format(output_dir, now, 'log.html')
            attch_files = []
            if os.path.exists(src_report_html) and os.path.exists(src_log_html):
                shutil.copy(src_report_html, tgt_report_html)
                shutil.copy(src_log_html, tgt_log_html)
                # with open(src_report_html, mode='r', encoding='utf-8') as fr, open(tgt_report_html, mode='w',
                #                                                                    encoding='utf-8') as fw:
                #     for line in fr:
                #         fw.write(line.replace('log.html', "{}_{}".format(now, 'log.html')))

                cont = read_file(tgt_report_html)
                attch_file = FileAttachment(name=os.path.basename(tgt_report_html), content=cont)
                attch_files.append(attch_file)

                cont = read_file(tgt_log_html)
                attch_file = FileAttachment(name=os.path.basename(tgt_log_html), content=cont)
                attch_files.append(attch_file)

                msg = build_msg(output_dir, now)
                # msg = build_html_body(output_dir, now)
                to_recipients = []
                for to_address in to_addresses:
                    if to_address: to_recipients.append(Mailbox(email_address=to_address))
                m = Message(
                    account=account,
                    subject=subject,
                    body=HTMLBody(msg),
                    to_recipients=to_recipients
                )
                for attch_file in attch_files:
                    m.attach(attch_file)
            else:
                raise Exception('The file report.html or log.html does not exist')
        else:
            raise Exception('The path {} does not exist'.format(output_dir))
        print("Start send...")
        m.send()
        print("Finish...")
    except Exception as e:
        raise Exception(str(e))


if __name__ == '__main__':
    pass
